package org.gwt.pluginframework.development;

import org.gwt.pluginframework.common.ComplexPlugin;
import org.gwt.pluginframework.common.event.CommonEvents;
import org.gwt.pluginframework.common.event.IPluginEvent;
import org.gwt.pluginframework.common.event.PluginEvent;
import org.gwt.pluginframework.common.event.PluginEventHandler;
import org.gwt.pluginframework.plugin.CustomEvents;
import org.gwt.pluginframework.plugin.PerspectiveCenterExtension;
import org.gwt.pluginframework.plugin.PerspectiveSouthExtension;

import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.Viewport;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;

public class DevelopmentPerspective extends ComplexPlugin {

	private static final long serialVersionUID = -2676990982178434828L;
	
	public static final String CENTER_EXTENSION_POINT = "center";
	public static final String SOUTH_EXTENSION_POINT = "south";

	BorderLayoutData centerData;
	BorderLayoutData southData;

	LayoutContainer main;
	
	@Override
	public void onInitialize() {
		registerEventHandler(new PluginEventHandler(CommonEvents.PLUGIN_MANAGER_STARTED_EVENT) {
			public void handle(IPluginEvent event) {
				long start = System.currentTimeMillis();
				manager.dispatch(new PluginEvent(CustomEvents.PERSPECTIVE_INITIALIZED_EVENT, 
						DevelopmentPerspective.this,
						new String[] { "time" }, 
						new Object[] { System.currentTimeMillis() - start }));		
			}
		});
	}
	
	@Override
	public void onStart() {
		Viewport v = new Viewport();
		v.setLayout(new FitLayout());
		
		constructBorderLayoutData();
		main = new LayoutContainer(new BorderLayout());
		main.setBorders(false);
	
		// center element must be supplied to render border layout
		main.add(((PerspectiveCenterExtension) extensions.get(
				CENTER_EXTENSION_POINT).get(0)).getWidget(), centerData);
		Widget south = ((PerspectiveSouthExtension) extensions.get(
				SOUTH_EXTENSION_POINT).get(0)).getWidget();
//		((ContentPanel) south).collapse();
		main.add(south, southData);
		
		v.add(main);

		RootPanel.get().add(v);
	}
	
	private void constructBorderLayoutData() {
		centerData = new BorderLayoutData(LayoutRegion.CENTER);
		centerData.setMargins(new Margins(5, 5, 5, 5));

		southData = new BorderLayoutData(LayoutRegion.SOUTH, 25);
		southData.setSplit(false);
		southData.setCollapsible(false);
		southData.setFloatable(false);
		southData.setMargins(new Margins(0, 5, 5, 5));
	}

	public void setupManifest() {
		manifest.setName("DevelopmentPerspective");
		manifest.setVersion("1.0");
	}
}
